define(["../common"], function() {
	require.config({
		paths: {
			echarts: './echarts-2.2.1'
	    }
	});
	var subTitle,timeType = 0,chartType = 0;
	  
	$("[id^='type_']").click(function() {
  		chartType = parseInt($(this).attr("id").split("_")[1]);
  		
  		$("[id^='type_']").removeClass("selected");
  		$(this).addClass("selected");
  		
  		var type = $(this).attr("id").split("_")[1];
  		$("[id^='title_']").hide();
  		$("#title_" + type).show();
  		
  		$("#chart").height(350).html("正在加载...");
  		
  		eval("type_" + chartType + "();");
	});
	  
	$("[id^='time_']").click(function() {
  		timeType = parseInt($(this).attr("id").split("_")[1]);
  		
  		$("[id^='time_']").removeClass("selected");
  		$(this).addClass("selected");
  		
  		$("#chart").height(350).html("正在加载...");
  		
  		setDateTime();
  		
  		eval("type_" + chartType + "()");
	});
	  
	setDateTime();
	type_0();
	  
	function setDateTime() {
	  	
		var date = new Date(),startTime, endTime, endText;
	  	
	  	// 只有当天走势图按以小时,其它都以天,注意此列的判定顺序
	  	// 注意下面startTime 和 endTime, 因为后台查询条件总是满足：>= startTime 和　< endTime
	  	if (chartType === 3 && timeType === 0) {
	  		// yyMMddhh
	  		
	  		startTime = date.format('yyMMdd') + "00";// 今天0时
	  		
	  		endText  = date.format('yyMMdd') + "23";
	  		
	  		date.setDate(date.getDate() + 1);// 加1天
	  		endTime = date.format('yyMMdd') + "00";// 明天0时
	  		
	  	} else if (timeType === 0) {
	  		// yyMMdd
	  		
	  		startTime = date.format('yyMMdd');// 今天
	  		
	  		endText = startTime;
	  		
	  		date.setDate(date.getDate() + 1);// 加1天
	  		endTime = date.format('yyMMdd');// 明天
	  		
	  	} else if (timeType === 1) {
	  		// yyMMdd
	  		
	  		var day = date.getDay() === 0 ? 7 : date.getDay();// 按习惯计法,星期日为一周最后一天
	  		date.setDate(date.getDate() - (day - 1));// 星期一
	  		startTime = date.format('yyMMdd');// 星期一
	  		
	  		date.setDate(date.getDate() + 6);// 加6天
	  		endText = date.format('yyMMdd');// 周日
	  		
	  		date.setDate(date.getDate() + 1);// 加1天
	  		endTime = date.format('yyMMdd');// 下周一
	  		
	  	} else if (timeType === 2) {
	  		// yyMMdd
	  		
			startTime = date.format('yyMM') + "01";// 当月1日
	  		
	  		date.setDate(1);
	  		date.setMonth(date.getMonth() + 1);
	  		date.setDate(date.getDate() - 1);
	  		endText = date.format('yyMMdd');// 当月最后一天
	  		
			date.setDate(date.getDate() + 1);// 下月1日
	  		endTime = date.format('yyMMdd');// 下月1日
	  	}
	  	
	  	$("#startTime").val(startTime);
	  	$("#endTime").val(endTime);
	  	if (timeType === 0) {
	  		subTitle = "20" + startTime;
	  		if (chartType === 3) {
	  			subTitle = subTitle.substring(0,6);//去掉＂时＂间
	  		}
	  	} else {
	  		subTitle = "20" + startTime + "~" + "20" + endText;
	  	}
	  	
	}
	  
	function type_0() {
	  	var callback = function(data) {
	      	
	      	if (data.status !== 0 || !data.result) {
	      		$("#chart").height(30).html("无数据显示");// (ie兼容处理)通过修改高度的方式,使上级标签的背景能显示(原改背景透明度无效)
	      		return;
	      	}
	      	var grv,// goodsReportView
	      	names = [],// goods name
	      	revenue = [],// 销售额
	      	profit = [],// 利润
	      	list = data.result;// goodsReportView Array
	      	for (var i in list) {
	       		grv = list[i];
	       		names.push(grv.name);
	       		revenue.push(grv.revenue);
	       		profit.push((grv.revenue - grv.cost).toFixed(2));
	       	}
	       	names.reverse();
	       	revenue.reverse();
	       	profit.reverse();
	       	
	    	var height = list.length * 24 + 150;
	       	$("#chart").height(height < 350 ? 350: height);
	       	
	      	var option = {
	      	  backgroundColor: '#ffffff',
	      	  title: {
	      	  	subtext: subTitle 
	      	  },
	      	  grid: {
	          	x: 160,
	          	y: 80,
	          	width: 450,
	          	borderWidth: 0
	          },
	          tooltip : {
	          	 formatter: '{a}：{c}￥',
	          	 textStyle: {
	          	 	fontSize: 12
	          	 }
	          },
	          legend: {
	          	  data:['利润', '销售额']
	          },
	          toolbox: {
	              show : true,
	              orient: 'vertical',
	              y: 'center',
	              feature : {
	                  restore : {show: true},
	                  saveAsImage : {show: true}
	              }
	          },
	          xAxis : [
	              {
	                  type : 'value',
	                  splitNumber: 10,
	              	  position: 'top',
	                  axisLine: {
	                  	lineStyle: {
	                  		color:'#ffffff'
	                  	}
	  		  		  },
	                  splitLine: {
	                  	lineStyle: {
	                        type: 'dashed'
	                    }  
	                  }
	              }
	          ],
	          yAxis : [
	              {
	                  type : 'category',
	                  position: 'left',
	                  axisLine: {
	                  	lineStyle: {
	                  		color:'#ffffff'
	                  	}
	  		  		  },
	  		  		  axisTick: {show:false},
	        		  	splitArea:{
	        		  		show:true,
	                      areaStyle: {
	                         	color: ["rgba(250,250,250,0.1)","rgba(200,200,200,0.1)"]
	                      }
	                  },
	                  splitLine: {show: false},
	                  data : names
	              },
	              {
	                  type : 'category',
	                  axisLine: {show:false},
	                  axisTick: {show:false},
	        		  	axisLabel: {show:false},
	        	      	splitArea: {show:false},
	                  splitLine: {show:false},
	                  data : names
	              }
	          ],
	          series : [
	              {
	                  name:'销售额',
	                  type:'bar',
	                  clickable: false,
	                  itemStyle : {normal: {color:'#E87C25',barBorderRadius: [3,3,3,3], label:{show:true}}},
	                  data:revenue
	              },
	              {
	                  name:'利润',
	                  type:'bar',
	                  clickable: false,
	                  yAxisIndex: 1,
	                  itemStyle : {normal: {color:'#27727B',barBorderRadius: [3,3,3,3],label:{show:false}}},
	                  data:profit
	              }
	              
	          ]
	      };
	          
	       require(
	            [
	                'echarts',
	                'echarts/chart/bar'
	            ],
	            function (ec) {
	                var myChart = ec.init(document.getElementById('chart'));
	                myChart.setOption(option);
	            }
	        );
	    };
	    loadRevenueGoodsesReport(callback);
	}
	  
	//####################################################
	function type_4() {
	  	var callback = function(data) {
	    	
	    	if (data.status !== 0 || !data.result) {
	        	$("#chart").height(30).html("无数据显示");// (ie兼容处理)通过修改高度的方式,使上级标签的背景能显示(原改背景透明度无效)
	    		return;
	    	}
	    	
	    	var grv,// goodsReportView
	    	names = [],// goods name
	    	losses = [],// 损耗
	    	list = data.result;// goodsReportView Array
	    	for (var i in list) {
	       		grv = list[i];
	       		names.push(grv.name);
	       		losses.push(grv.loss);
	       	}
	       	names.reverse();
	       	losses.reverse();
	       	
	    	var height = list.length * 24 + 150;
	       	$("#chart").height(height < 350 ? 350: height);
	       	
	    	var option = {
	              backgroundColor: '#ffffff',
	      	  	  title: {
		      	  	subtext: subTitle 
		      	  },
		      	  grid: {
	              	x: 200,
	              	y: 80,
	              	width: 450,
	              	borderWidth: 0,
	              },
	              tooltip : {
	              	 formatter: '{a}：{c}￥',
	              	 textStyle: {
	              	 	fontSize: 12
	              	 }	
	              },	
	              legend: {
	              	  data:['损耗金额']
	              },
	              toolbox: {
	                  show : true,
	                  orient: 'vertical',
	                  y: 'center',
	                  feature : {
	                      restore : {show: true},
	                      saveAsImage : {show: true}
	                  }
	              },
	              xAxis : [
	                  {
	                      type : 'value',
	                      splitNumber: 10,
	                  	  position: 'top',
	                      axisLine: {
	                      	lineStyle: {
	                      		color:'#ffffff'
	                      	}
	      		  	  },
	                      splitLine: {
	                      	lineStyle: {
	                            type: 'dashed'
	                        }  
	                      },
	                  }
	              ],
	              yAxis : [
	                  {
	                      type : 'category',
	                      position: 'left',
	                      axisLine: {
	                      	lineStyle: {
	                      		color:'#ffffff'
	                      	}
	      		  },
	      		  axisTick: {show:false},
	            		  splitArea:{show:true,
	                          areaStyle: {
	                              color: ["rgba(250,250,250,0.1)","rgba(200,200,200,0.1)"]
	                          }
	                      
	                      },
	                      splitLine: {show: false},
	                      data : names
	                  }
	              ],
	              series : [
	                  {
	                      name:'损耗金额',
	                      type:'bar',
	                      clickable: false,
	                     itemStyle : {normal: {color:'#E87C25',barBorderRadius: [3,3,3,3],label:{show:false}}},
	                      data:losses
	                  }
	                  
	              ]
	          };
	        
	        require(
	            [
	                'echarts',
	                'echarts/chart/bar'
	            ],
	            function (ec) {
	                var myChart = ec.init(document.getElementById('chart'));
	                myChart.setOption(option);
	            }
	        );
	        
	    };
	    
	    loadLossGoodsesReport(callback);
	}
	  
	  
	//#####################################################
	function type_2() {
	  	var callback = function(data) {
	    	// 后台始终返回了一个空记录(只带name),因此作此判断(!data.result[0].revenue)
	    	if (data.status !== 0 || !data.result || !data.result[0].revenue) {
	    		$("#chart").height(30).html("无数据显示");// (ie兼容处理)通过修改高度的方式,使上级标签的背景能显示(原改背景透明度无效)
	    		return;
	    	}
	    	
	    	var grv = data.result[0],// goodsReportView
	    	revenue = grv.revenue,// 销售额
	   		cost = grv.cost.toFixed(2),// 成本
	   		loss = grv.loss.toFixed(2);// 损耗
	   		profit = (grv.revenue - grv.cost - grv.loss).toFixed(2);// 利润;
	    	
	    	// TODO 便于有效观察，如果利润小于0，应切换为柱形图
	    	
	    	var option = {
	          backgroundColor: '#ffffff',
	      	  color: ['#27727B','#E87C25','#b8860b'],
	          title: {
	      	  	subtext: subTitle 
	      	  },
	      	  tooltip: {
	              formatter: '{a} <br/>{b} : {c} ({d}%)'
	          },
	          legend: {
	              selectedMode: false,
	          	  data:['利润','成本','损耗']
	          },
	          toolbox: {
	              show : true,
	              orient: 'vertical',
	              y: 'center',
	              feature : {
	                  restore : {show: true},
	                  saveAsImage : {show: true}
	              }
	          },
	          series : [
	              {
	                  name:'销售额：' + revenue,
	                  type:'pie',
	                  radius : '55%',
	                  center: ['50%', '50%'],
	                  selectedOffset: 10,
	                  selectedMode: 'multiple',
	                  data:[
	                      {value: profit, name:'利润'},
	                      {value: cost, name:'成本'},
	                      {value: loss, name:'损耗'}
	                  ]
	              }
	          ]
	      };
	      require(
	          [
	              'echarts',
	              'echarts/chart/pie'
	          ],
	          function (ec) {
	              var myChart = ec.init(document.getElementById('chart'));
	              myChart.setOption(option);
	          }
	      );
	     
	    };
	    loadSumReport(callback);
	}
	  
	  
	// #####################################################################
	function type_1() {
		var callback = function (data) {
        	
        	if (data.status !== 0 || !data.result) {
        		$("#chart").height(30).html("无数据显示");// (ie兼容处理)通过修改高度的方式,使上级标签的背景能显示(原改背景透明度无效)
        		return;
        	}
        	
        	var list = data.result,
        	grv,// goodsReportView
        	names = [],// store name
        	revenue = [],// 销售额
        	profit = []; // 利润=销售额-成本-损耗
        	
        	for (var i in list) {
           		grv = list[i];
           		names.push(grv.name);
           		revenue.push(grv.revenue);
           		profit.push((grv.revenue - grv.cost - grv.loss).toFixed(2));
           	}
        	
        	var option = {
              backgroundColor: '#ffffff',
      	  	  title: {
	      	  	subtext: subTitle 
	      	  },
	      	  grid: {
              	width: 550
              },
              tooltip : {
              	formatter: '{a}：{c}￥',
              	textStyle: {
              	 	fontSize: 12
              	}
              },
              legend: {
              	data:['销售额','利润']
              },
              toolbox: {
                  show : true,
                  orient: 'vertical',
                  y: 'center',
                  feature : {
                      restore : {show: true},
                      saveAsImage : {show: true}
                  }
              },
              xAxis : [
                  {
                      type : 'category',
                      splitLine:{show: false},
                      data : names
                  },
                  {
                      type : 'category',
                      axisLine: {show:false},
                      axisTick: {show:false},
              		axisLabel: {show:false},
              	    splitArea: {show:false},
                      splitLine: {show:false},
                      data : names
                  }
              ],
              yAxis : [
                  {
                    splitNumber: 10,
                    splitLine:{show: false},
                    splitArea:{show:true,
                        areaStyle: {
                            color: ["rgba(250,250,250,0.1)","rgba(200,200,200,0.1)"]
                        }
                    
                    }
                  }
              ],
              series : [
                  {
                      name:'利润',
                      type:'bar',
                      clickable: false,
                      itemStyle : {normal: {color:'#27727B',barBorderRadius: [3,3,3,3],label:{show:true}}},
                      data:profit
                  },{
                      name:'销售额',
                      type:'bar',
                      clickable: false,
                      xAxisIndex: 1,
                      itemStyle : {normal: {color:'#E87C25',barBorderRadius: [3,3,3,3], label:{show:true}}},
                      data:revenue
                  }
              ]
            };
            require(
                [
                    'echarts',
                    'echarts/chart/bar'
                ],
                function (ec) {
                    var myChart = ec.init(document.getElementById('chart'));
                    myChart.setOption(option);
                }
            );
        };
        loadCheckersReport(callback);
	}
	  

	// ############################################
	function type_3() {
	  	var callback = function(data) {
	      	
	      	if (data.status !== 0) {
	      		$("#chart").height(30).html("无数据显示");// (ie兼容处理)通过修改高度的方式,使上级标签的背景能显示(原改背景透明度无效)
	      		return;
	      	}
	      	
	      	var names = getTimeNames(),
	      	labels = [];
	      	
			if (timeType === 0) {// 一天每个小时
	      		for (var i = 0; i< 24; i++) {
	      			labels.push(i);
	      		}
	      	
	      	} else if (timeType === 1) {// 一星期每天
	      		labels = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
	      	
	      	} else if (timeType === 2) {// 一个月每天	
	      		var date = new Date();
	      		days = new Date(date.getFullYear(), date.getMonth(), 0).getDate();// 当月天数
	      		for (var i = 1; i< days; i++) {
	      			labels.push(i);
	      		}
	      	}
	      	
	      	var list = data.result,// goodsReportView Array
	      	grv,// goodsReportView
	      	revenue = [],
	      	maxRevenue = 0;
	      	has = false;
	      	for (var n = 0; n < names.length; n++) {
	      		has = false;
	      		if (list && list.length > 0) {
	      			for (var i in list) {
			       		grv = list[i];
			       		if (grv && names[n] === grv.name) {
			       			has = true;
			       			revenue.push(grv.revenue);
			       			if (maxRevenue < grv.revenue) {
			       				maxRevenue = grv.revenue;
			       			}
			       			list[i] = null;
			       			break;
			       		}
			       	}
	      		} 
	      		if (!has) {
	      			revenue.push(0);
	      		}
	      	}
	       	
	      	var option = {
	            backgroundColor: '#ffffff',
	      	  	title: {
	      	  		subtext: subTitle 
	      	  	},
	      	  	grid: {
	        	  	width: 580
	        	},
	        	tooltip : {
	                trigger: 'axis'
	            },
	            legend: {
	              data:['销售额']
	            },
	            toolbox: {
	                show : true,
	                orient: 'vertical',
	              	y: 'center',
	              	feature : {
	                    restore : {show: true},
	                    saveAsImage : {show: true}
	                }
	            },
	            xAxis : [
	                {
	                    type : 'category',
	                    splitLine:{show: false},
	                    //axisLabel: {rotate:45},
	                    //boundaryGap : false,
	                    data : labels
	                }
	            ],
	            yAxis : [
	                {
	                    max: maxRevenue,
	                    splitLine:{show: false},
	                    splitArea:{show:true,
	                        areaStyle: {
	                            color: ["rgba(250,250,250,0.1)","rgba(200,200,200,0.1)"]
	                        }              
	                    }
	                }
	            ],
	            series : [
	                {
	                    name:'销售额',
	                    type:'line',
	                    smooth: true,
	                    symbol: 'none',
	                    data:revenue
	                }
	            ]
	        };
	        require(
	            [
	                'echarts',
	                'echarts/chart/line'
	            ],
	            function (ec) {
	                var myChart = ec.init(document.getElementById('chart'));
	                myChart.setOption(option);
	            }
	        );
	    };
	    loadDaysReport(callback);
	}
	  
	  
	// ################################################

	function getTimeNames() {
		
		var startTime =$("#startTime").val();
		var endTime =$("#endTime").val();
		var startYear,startMon = 0,startDate = 0,startHour = 0,endYear,endMon = 0,endDate = 0,endHour = 0;
		startYear = "20" + startTime.substr(0,2);
		endYear = "20" + endTime.substr(0,2);
		
		// 有月
		if (startTime.length > 2) {
			startMon = startTime.substr(2,2);
			endMon = endTime.substr(2,2);
			// 有天
			if (startTime.length > 4) {
				startDate = startTime.substr(4,2);
				endDate = endTime.substr(4,2);
				// 有小时
				if (startTime.length > 6) {
					startHour = startTime.substr(6,2);
					endHour = endTime.substr(6,2);
					
					//...
				}
			}
		}
		
		var start = new Date(startYear, startMon > 0 ? (parseInt(startMon) -1) : 0, startDate, startHour);
		var end = new Date(endYear, endMon > 0 ? (parseInt(endMon) -1) : 0, endDate, endHour);
		var names = [];
		while(start.getTime() <= end.getTime()) {
			if (startTime.length === 2) {
				names.push(start.format('yy'));
				start.setFullYear(start.getFullYear() + 1);
			} else if (startTime.length === 4) {
				names.push(start.format('yyMM'));
				start.setMonth(start.getMonth() + 1);
			} else if (startTime.length === 6) {
				names.push(start.format('yyMMdd'));
				start.setDate(start.getDate() + 1);
			} else if (startTime.length === 8) {
				names.push(start.format('yyMMddhh'));
				start.setHours(start.getHours() + 1);
			} 
		}
		return names;
	}


	function loadRevenueGoodsesReport(callback) {
		$.post(g_shopDomain + "/goodsReport/revenueGoodses/json", $("form").serialize(), callback);
	}

	function loadLossGoodsesReport(callback) {
		$.post(g_shopDomain + "/goodsReport/lossGoodses/json", $("form").serialize(), callback);
	}

	function loadCheckersReport(callback) {
		$.post(g_shopDomain + "/goodsReport/checkers/json", $("form").serialize(), callback);
	}

	function loadSumReport(callback) {
		$.post(g_shopDomain + "/goodsReport/sum/json", $("form").serialize(), callback);
	}

	function loadDaysReport(callback) {
		$.post(g_shopDomain + "/goodsReport/days/json", $("form").serialize(), callback);
	}
});
  